package com.woniuxy.yoga.commons.core.util;

import cn.hutool.extra.qrcode.QrCodeUtil;
import com.woniuxy.yoga.commons.core.cofig.QRConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URL;

@Component
public class QRCodeUtil {
    @Autowired
    private QRConfig qrConfig;

    /**
     * 生成二维码
     * @param content
     * @return
     */
    public InputStream generatePng(String content) throws Exception {
        if (content == null) throw new Exception("二维码内容为空");
        byte[] bytes = QrCodeUtil.generatePng(content, qrConfig.qrConfig());
        return new ByteArrayInputStream(bytes);
    }

    /**
     * 解析二维码
     * @param urlPath
     * @return
     * @throws Exception
     */
    public String decode(String urlPath) throws Exception {
        if (urlPath == null) throw new Exception("二维码图片地址为空");
        URL url = new URL(urlPath);
        return QrCodeUtil.decode(url.openStream());
    }
}
